from flask import jsonify
import json
from pathlib import Path
from ahp_engine import is_valid_judgment_matrix


class PresetMatrixManager:
    def __init__(self, file_path=None):
        self.file_path = file_path or Path(__file__).parent / 'config' / 'preset_matrices.json'
        with open(self.file_path, 'r', encoding='utf-8') as f:
            self.presets = json.load(f)

    def get_all_keys(self):
        """获取所有可用 key"""
        return list(self.presets.keys())

    def get_preset_info(self, key):
        """获取某个预设的基本信息"""
        preset = self.presets.get(key)
        if not preset:
            raise KeyError(f"预设 '{key}' 不存在")
        return {
            "name": preset["name"],
            "description": preset["description"],
            "tags": preset["tags"]
        }

    def get_matrix(self, key):
        """获取用于计算的浮点型矩阵"""
        return self.presets[key].get("matrix")

    def get_matrix_str(self, key):
        """获取用于展示的字符串型矩阵"""
        return self.presets[key].get("matrix_str")

    def validate_all(self):
        """校验所有矩阵是否合法"""
        invalid = []
        for key in self.presets:
            matrix = self.get_matrix(key)
            if not is_valid_judgment_matrix(matrix):
                invalid.append(key)
        return invalid

    def add_preset(self, key, data):
        """
        添加新的预设矩阵
        data: dict 包含 name, description, tags, matrix, matrix_str
        """
        if key in self.presets:
            raise ValueError(f"预设 '{key}' 已存在")
        self.presets[key] = data
        self._save()

    def _save(self):
        """保存回文件"""
        with open(self.file_path, 'w', encoding='utf-8') as f:
            json.dump(self.presets, f, ensure_ascii=False, indent=2)

    def convert_matrix_str_to_float(self, matrix_str):
        """将字符串矩阵转为浮点型"""
        result = []
        for row in matrix_str:
            new_row = []
            for cell in row:
                try:
                    new_row.append(float(cell))
                except ValueError:
                    parts = cell.split('/')
                    if len(parts) == 2:
                        new_row.append(round(float(parts[0]) / float(parts[1]), 6))
                    else:
                        raise ValueError(f"无法解析单元格: {cell}")
            result.append(new_row)
        return result
    

# http_utils
# utils/response_utils.py
def make_response(code=200, status="success", message="", data=None):
    """
    统一返回格式
    :param code: HTTP 状态码
    :param status: 状态标识(success/error/warning)
    :param message: 提示信息
    :param data: 返回数据
    :return: (response, code)
    """
    response = {
        "code": code,
        "status": status,
        "message": message
    }
    if data is not None:
        response["data"] = data
    return jsonify(response), code